package JMF;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.media.rtp.*;
import java.net.*;
import java.util.Vector;

import javax.media.*;
import javax.media.control.TrackControl;
import javax.media.datasink.DataSinkEvent;
import javax.media.datasink.DataSinkListener;
import javax.media.format.AudioFormat;
import javax.media.protocol.*;
import javax.swing.JPanel;

import com.sun.media.rtp.RTPSessionMgr;

public class examplePanel extends JPanel implements ActionListener, ControllerListener
{
	private static final long serialVersionUID = 1L;
	private boolean configured = false;
	private boolean realized = false;
	private Component visualComponent;
	private Player player;
	
	public examplePanel()
	{
		fucktardShit();
		System.out.println("Creating player");
		//MediaLocator ml = new MediaLocator("rtp://10.11.38.130:49152/audio/1");
		
		try {
			System.out.println("Trying to create player");
//			player = Manager.createPlayer(Manager.createDataSource(ml));
		} catch (Exception e) {
			System.out.println(e);
		} 
		//player.addControllerListener(this);
		
//		player.start();
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
	}

	public void actionPerformed(ActionEvent e)
	{

	}

	public synchronized void controllerUpdate(ControllerEvent evt) {
		if (evt instanceof RealizeCompleteEvent) {
			realized = true;
		} else  if (evt instanceof ConfigureCompleteEvent) {
			configured = true;
		} else if (evt instanceof EndOfMediaEvent) {
			System.exit(0);
		} else {
			// System.out.println(evt.toString());
		}
	}
	
	public void createRTP(){
		try {
			
			MediaLocator ml = new MediaLocator(new URL("file:///C:/01_Intro.wav"));
			DataSource ds  = Manager.createDataSource(ml);
			ds.connect();
			ds.start();
			
			//Processor p = Manager.createProcessor(new URL("file:///C:/01_Intro.wav"));
			
			
			
			Buffer b = new Buffer();
			
			if(ds instanceof PullDataSource){
				System.out.println("LOL");
				//PushBufferDataSource();
				
			}
			
			DataSink dataSink = Manager.createDataSink((PushBufferDataSource)ds, ml);
			
			
			// create the RTP Manager
			 RTPManager rtpManager = RTPManager.newInstance();
			 
			 // create the local endpoint for the local interface on
			 // any local port
			 SessionAddress localAddress = new SessionAddress();
			 
			 // initialize the RTPManager
			 rtpManager.initialize( localAddress);

			 // add the ReceiveStreamListener if you need to receive data
			 // and do other application specific stuff
			 // ...
			 
			 // specify the remote endpoint of this unicast session 
			 // the address string and port numbers in the following lines
			 // need to be replaced with your values.
			 InetAddress ipAddress = InetAddress.getByName( "192.168.1.33");
			 
			 SessionAddress remoteAddress = new SessionAddress( ipAddress, 3000);

			 // open the connection
			 rtpManager.addTarget( remoteAddress);
			 
			 // create a send stream for the output data source of a processor
			 // and start it
			 
			 SendStream sendStream = rtpManager.createSendStream( ds, 1);
			 sendStream.start();
			 
			 // send data and do other application specific stuff,
			 // ...
			 
			 // close the connection if no longer needed.
			 rtpManager.removeTarget( remoteAddress, "client disconnected.");
			 
			 // call dispose at the end of the life-cycle of this RTPManager so
			 // it is prepared to be garbage-collected.
			 rtpManager.dispose();
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void WAVESource(){
		
	}
	
	private void fucktardShit(){
		try{
			
		 Format[] FORMATS = new Format[] {
			new AudioFormat(AudioFormat.MPEG_RTP)};
			 
		 MediaLocator mediaLocator = new MediaLocator("rtp://10.11.38.247:49150/audio");
		 System.out.println(mediaLocator.toExternalForm());
		 DataSource source = Manager.createDataSource(new MediaLocator(
				 new URL("file:///C:/01_Intro.wav")));
		 //DataSource ds  = Manager.createDataSource(mediaLocator);
		 ContentDescriptor CONTENT_DESCRIPTOR =
				 new ContentDescriptor(ContentDescriptor.RAW_RTP);
		
		 Processor mediaProcessor = Manager.createProcessor(source);
		 
		 mediaProcessor.addControllerListener(this);
		 

		 
		 mediaProcessor.configure();
		 
		 
			while (! configured) {
				try {
					Thread.currentThread().sleep(100L);;
				} catch (InterruptedException e) {
					// ignore
				}
			}
			mediaProcessor.setContentDescriptor(new ContentDescriptor(ContentDescriptor.RAW_RTP));
			setTrackFormat(mediaProcessor);
			mediaProcessor.realize();
			
		 
		 DataSink dataSink = Manager.createDataSink(mediaProcessor.getDataOutput(),
				 mediaLocator);
		 
		 dataSink.addDataSinkListener(new DataSinkListener(){

			@Override
			public void dataSinkUpdate(DataSinkEvent arg0) {
				System.out.println(arg0.toString());
				System.out.println("IN DATA SINK");
			}
			 
		 });
		 
		 System.out.println("HERE");
		 mediaProcessor.start();
		 dataSink.open();
		 dataSink.start();
		 
		}
		catch(Exception e){
			System.out.println(e);
		}
		
	}
	
	private void setTrackFormat(Processor p) {
		// Get the tracks from the processor
		TrackControl [] tracks = p.getTrackControls();
		// Do we have atleast one track?
		if (tracks == null || tracks.length < 1) {
			System.out.println("Couldn't find tracks in processor");
			System.exit(1);
		}

		// Set the output content descriptor to RAW_RTP
		// This will limit the supported formats reported from
		// Track.getSupportedFormats to only valid RTP formats.
		ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
		p.setContentDescriptor(cd);

		Format supported[];
		Format chosen;
		boolean atLeastOneTrack = false;

		// Program the tracks.
		for (int i = 0; i < tracks.length; i++) {
			Format format = tracks[i].getFormat();
			System.out.println("The track format is " +format.getEncoding());
			if (tracks[i].isEnabled()) {
				supported = tracks[i].getSupportedFormats();
				for (int n = 0; n < supported.length; n++)
					System.out.println("Supported format: " + supported[n]);

				// We've set the output content to the RAW_RTP.
				// So all the supported formats should work with RTP.
				// We'll just pick the first one.

				if (supported.length > 0) {
					chosen = supported[0]; // this is where I tried changing formats
					tracks[i].setFormat(chosen);
					System.err.println("Track " + i + " is set to transmit as: " +chosen);
					atLeastOneTrack = true;
				} else
					tracks[i].setEnabled(false);
			} else
				tracks[i].setEnabled(false);
		}
	}
}